<template>
  <div>
    <van-search placeholder="请输入搜索关键词" v-model="prads" @keypress.enter="setHistory">
      <template #left>
        <van-icon name="arrow-left" size="25" @click="$router.go(-1)" />
      </template>
    </van-search>
    <div class="room" v-show="historyFlag">
      <p>
        <span>历史记录</span>
        <van-icon name="delete" size="20" @click="removeHistory"></van-icon>
      </p>
      <div class="toom">
        <div class="item" v-for="(item,index) in historyList" :key="index">{{item}}</div>
      </div>
    </div>
    <Popul :populList="searchGoods" v-show="!historyFlag"></Popul>
  </div>
</template>

<script>
import Popul from "../../components/home/Popul";
export default {
  data() {
    return {
      populList: [],
      prads: "",
      historyList: [], //历史纪录
      historyFlag: true,
    };
  },
  components: {
    Popul,
  },
  mounted() {
    this.popul();
    this.getHistory();
  },
  computed: {
    //商品的模糊搜索
    searchGoods() {
      //先把商品所有的数据付给变量
      let data = this.populList;

      //搜索的关键字为空的时候
      if (this.prads == "") {
        this.historyFlag = true; //历史纪录显示
        return [];
      }

      this.historyFlag = false; //历史纪录隐藏
      return data.filter((item) => {
        return item.name.indexOf(this.prads) > -1;
      });
    },
  },
  created() {},
  methods: {
    //   数据
    popul() {
      this.$axios
        .get("https://api.it120.cc/small4/shop/goods/list")
        .then((res) => {
          console.log(res);
          this.populList = res.data;
        });
    },
    // 历史记录
    getHistory() {
      let data = localStorage.getItem("shuju");

      if (data != null) {
        this.historyList = JSON.parse(data); //解析数据，返回给history
      } else {
        this.historyList = [];
      }
    },
    //设置历史记录信息
    setHistory() {
      if (this.prads == "") {
        return false;
      }
      //插入记录到数组的第一条
      this.historyList.unshift(this.prads);

      if (this.historyList.length > 8) {
        this.historyList.pop();
      }

      localStorage.setItem("shuju", JSON.stringify(this.historyList));
      this.prads = "";
    },
    removeHistory() {
      localStorage.removeItem("shuju");
      this.getHistory();
    },
  },
};
</script>

<style scoped lang="less">
.room {
  span {
    font-size: 0.2rem;
  }
  p {
    display: flex;
    justify-content: space-between;
  }
}
.toom {
  display: flex;
  // justify-content: space-around;
  flex-wrap: wrap;
  .item {
    width: 24%;
    border-radius: 0.5rem;
    background-color: #f4f4f4;
    font-size: 0.4rem;
    text-align: center;
  }
}
</style>
